<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use app\common\model\Question;
use EasyWeChat\Foundation\Application;
use addons\wechat\library\Config as ConfigService;

class Course extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function read($course_id)
    {
        $course = Db::name('course')->where(['id' => $course_id])->find();
        $this->assign('course', $course);
        $this->assign('title', '阅读');
        return $this->view->fetch();
    }

    /**
     * 课后练习
     * @return [type] [description]
     */
    public function question()
    {
        $questions = Question::with('options')->order('id asc')->select();
        $this->assign('questions', $questions);
        $this->assign('title', '课后练习');
        return $this->view->fetch();
    }

    public function handout($id)
    {
        $course = Db::name('course')->field('id, paraphrase')->where(['id' => $id])->find();
        $this->assign('course', $course);
        $this->assign('title', '本章讲义');
        return $this->view->fetch();
    }

    public function complete()
    {
        if(request()->isPost()) {
            $data = input('post.data/a');
            $insertData = [];
            foreach ($data as $k => $v) {
                if(is_array($v)) {
                    $insertData[$k] = $v;
                }
            }
            $re = Db::name('user_options')->insert([
                'user_id' => $this->auth->id,
                'options' => json_encode($insertData),
                'create_time' => time()
            ]);
            if($re !== false) {
                $this->success('ok');
            }else{
                $this->error('false');
            }
        }
        $app = new Application(ConfigService::load());
        $js = $app->js;
        $this->assign('js', $js);
        $this->assign('title', '打卡完成');
        return $this->view->fetch();
    }

}
